package com.smproject.exception;

import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.core.util.StrUtil;
import com.smproject.common.ResultEntity;
import com.smproject.common.ResultMsg;
import com.sun.org.apache.xpath.internal.operations.Bool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.naming.AuthenticationException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.ValidationException;
import java.util.List;
import java.util.Objects;

/**
 * 统一的异常捕获
 * @author hu.liang
 * @Date 2019/1/11 0011
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 统一抛出异常
     * @param request
     * @param e
     * @param response
     * @return
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity exceptionHandler(HttpServletRequest request, Exception e, HttpServletResponse response) {
        log.error(e.getMessage());
        log.error(e.getLocalizedMessage());
        e.printStackTrace();
        ResultEntity statusDto = new ResultEntity();
        String errorMsg = "接口调用成功!";
        statusDto.setStatus(false);
        ResultEntity result=new ResultEntity(statusDto,Boolean.FALSE,errorMsg,null);
        if(e instanceof ModelVailException){
            statusDto = new ResultEntity();
            statusDto.setStatus(false);
            statusDto.setMsg(e.getMessage());
            return new ResponseEntity<ResultEntity>(new ResultEntity(statusDto,Boolean.FALSE,errorMsg,null), HttpStatus.OK);
        }

        if(e instanceof ValidateException){
            statusDto = new ResultEntity();
            statusDto.setStatus(false);
            statusDto.setMsg(e.getMessage());
            return new ResponseEntity<ResultEntity>(new ResultEntity(statusDto,Boolean.FALSE, ResultMsg.MSG_OK_200.toString(),null), HttpStatus.OK);
        }
        //抛javax.validation.ValidationException
        if(e instanceof ValidationException){
            statusDto = new ResultEntity();
            statusDto.setStatus(false);
            statusDto.setMsg(e.getCause().getMessage());
            return new ResponseEntity<ResultEntity>(new ResultEntity(statusDto,Boolean.FALSE,ResultMsg.MSG_OK_200.toString(),null), HttpStatus.OK);
        }
        if(e instanceof HttpMessageNotReadableException){
            statusDto = new ResultEntity();
            statusDto.setStatus(false);
            statusDto.setMsg("你所传的参数无法解析或者你在调用必须传递参数的接口中没有传递任何参数!");
            return new ResponseEntity<ResultEntity>(new ResultEntity(statusDto, Boolean.FALSE,ResultMsg.MSG_BAD_REQUEST_400.toString(),null), HttpStatus.BAD_REQUEST);
        }
        if(e instanceof RuntimeException){
            statusDto.setMsg("系统运行报错，请联系超级管理！");
            return new ResponseEntity(result, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        if(e instanceof AuthenticationException){
            statusDto.setMsg(e.getMessage());
            return new ResponseEntity(result, HttpStatus.UNAUTHORIZED);
        }
        return new ResponseEntity(result, HttpStatus.INTERNAL_SERVER_ERROR);
    }



    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResponseEntity<ResultEntity> validErrorHandler(MethodArgumentNotValidException exception){
        StringBuffer errorMsg = new StringBuffer();
        ResultEntity statusDto = new ResultEntity();
        List<ObjectError> errors = exception.getBindingResult().getAllErrors();
        for(int i=0;i<errors.size();i++){
            errorMsg.append(errors.get(i).getDefaultMessage()+",");
        }
        String message = errorMsg.toString();
        if(StrUtil.isNotBlank(message)){
            message = message.substring(0,message.length()-1);
        }
        statusDto.setMsg(message);
        return new ResponseEntity<ResultEntity>(new ResultEntity(statusDto,Boolean.TRUE,ResultMsg.MSG_OK_200.toString(),null), HttpStatus.OK);
    }
}
